<template>
  <div class="auth-container">
    <!-- 左侧图片展示区 -->
    <div class="left-section">
      <div class="brand-content">
        <h2 class="brand-title">开启你的旅程</h2>
        <p class="brand-subtitle">探索世界，记录美好时光</p>
        <div class="feature-list">
          <div class="feature-item">
            <el-icon :size="24">
              <Promotion />
            </el-icon>
            <span>智能行程规划</span>
          </div>
          <div class="feature-item">
            <el-icon :size="24">
              <Picture />
            </el-icon>
            <span>精彩瞬间分享</span>
          </div>
          <div class="feature-item">
            <el-icon :size="24">
              <Location />
            </el-icon>
            <span>全球目的地推荐</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧表单区 -->
    <div class="right-section">
      <div class="form-container">
        <h1 class="site-name">Koala旅行</h1>

        <!-- 登录表单 -->
        <transition name="fade" mode="out-in">
          <div v-if="currentView === 'login'" key="login" class="form-wrapper">
            <div class="form-header">
              <h2>欢迎回来</h2>
              <p>登录您的账户继续旅程</p>
            </div>

            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" @submit.prevent="handleLogin">
              <el-form-item prop="userName">
                <el-input v-model="loginForm.userName" placeholder="请输入用户名或邮箱" size="large" clearable>
                  <template #prefix>
                    <el-icon>
                      <User />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" size="large" show-password
                  clearable>
                  <template #prefix>
                    <el-icon>
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <div class="form-options">
                <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
                <el-link type="primary" :underline="false" @click="currentView = 'forgot'">忘记密码？</el-link>
              </div>

              <el-button type="primary" size="large" class="submit-btn" native-type="submit" :loading="loading">
                登录
              </el-button>
            </el-form>

            <div class="form-footer">
              <span>还没有账户？</span>
              <el-link type="primary" :underline="false" @click="currentView = 'register'">立即注册</el-link>
            </div>
          </div>

          <!-- 注册表单 -->
          <div v-else-if="currentView === 'register'" key="register" class="form-wrapper">
            <div class="form-header">
              <h2>创建账户</h2>
              <p>加入我们，开始你的旅行故事</p>
            </div>

            <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules"
              @submit.prevent="handleRegister">
              <el-form-item prop="userName">
                <el-input v-model="registerForm.userName" placeholder="请输入用户名" size="large" clearable>
                  <template #prefix>
                    <el-icon>
                      <User />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="email">
                <el-input v-model="registerForm.email" placeholder="请输入邮箱" size="large" clearable>
                  <template #prefix>
                    <el-icon>
                      <Message />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="请输入密码（至少6位）" size="large"
                  show-password clearable>
                  <template #prefix>
                    <el-icon>
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" size="large"
                  show-password clearable>
                  <template #prefix>
                    <el-icon>
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="agree">
                <el-checkbox v-model="registerForm.agree">
                  我同意
                  <el-link type="primary" :underline="false">服务条款</el-link>
                  和
                  <el-link type="primary" :underline="false">隐私政策</el-link>
                </el-checkbox>
              </el-form-item>

              <el-button type="primary" size="large" class="submit-btn" native-type="submit" :loading="loading">
                注册
              </el-button>
            </el-form>

            <div class="form-footer">
              <span>已有账户？</span>
              <el-link type="primary" :underline="false" @click="currentView = 'login'">立即登录</el-link>
            </div>
          </div>

          <!-- 重置密码表单 -->
          <div v-else key="forgot" class="form-wrapper">
            <div class="form-header">
              <h2>重置密码</h2>
              <p>请输入账户信息以重置密码</p>
            </div>

            <el-form ref="forgotFormRef" :model="forgotForm" :rules="forgotRules" @submit.prevent="handleForgot">
              <el-form-item prop="userName">
                <el-input v-model="forgotForm.userName" placeholder="请输入用户名" size="large" clearable>
                  <template #prefix>
                    <el-icon>
                      <User />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="email">
                <el-input v-model="forgotForm.email" placeholder="请输入注册时的邮箱" size="large" clearable>
                  <template #prefix>
                    <el-icon>
                      <Message />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="newPassword">
                <el-input v-model="forgotForm.newPassword" type="password" placeholder="请输入新密码（至少6位）" size="large"
                  show-password clearable>
                  <template #prefix>
                    <el-icon>
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="confirmPassword">
                <el-input v-model="forgotForm.confirmPassword" type="password" placeholder="请再次输入新密码" size="large"
                  show-password clearable>
                  <template #prefix>
                    <el-icon>
                      <Lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-button type="primary" size="large" class="submit-btn" native-type="submit" :loading="loading">
                重置密码
              </el-button>
            </el-form>

            <div class="form-footer">
              <span>想起密码了？</span>
              <el-link type="primary" :underline="false" @click="currentView = 'login'">返回登录</el-link>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Promotion, Picture, Location } from '@element-plus/icons-vue'
import {useUserStore} from "@/store/user/index.js";
import {useRoute, useRouter} from "vue-router";
import {modifyPassword, register} from "@/api/user/index.js";

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const currentView = ref('login')
const loading = ref(false)
const loginFormRef = ref()
const registerFormRef = ref()
const forgotFormRef = ref()

const loginForm = reactive({
  userName: '',
  password: '',
  remember: false
})

const registerForm = reactive({
  userName: '',
  email: '',
  password: '',
  confirmPassword: '',
  agree: false
})

const forgotForm = reactive({
  userName: '',
  email: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
const validateRegisterPassword = (_rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validateForgotPassword = (_rule, value, callback) => {
  if (value !== forgotForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const loginRules = {
  userName: [{ required: true, message: '请输入用户名或邮箱', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const registerRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateRegisterPassword, trigger: 'blur' }
  ],
  agree: [{ required: true, message: '请阅读并同意服务条款', trigger: 'change' }]
}

const forgotRules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateForgotPassword, trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  await loginFormRef.value.validate( async (valid) => {
    if (valid) {
      loading.value = true

      await userStore.login({ user : loginForm} ,  route.query.redirect || '/')
      loading.value = false

      setTimeout(() => {
        router.push(route.query.redirect || '/')
      } , 100)
    }
  })
}

const handleRegister = async () => {
  await registerFormRef.value.validate( async (valid) => {
    if (valid) {
      loading.value = true

      try {
        const res = await register(registerForm)
        ElMessage.success('注册成功')
        currentView.value = 'login'

      } finally {
        loading.value = false
      }

    }
  })
}

const handleForgot = async () => {
  await forgotFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        const res = await modifyPassword(forgotForm)
        ElMessage.success('密码重置成功，请使用新密码登录')
        currentView.value = 'login'
      } finally {
        loading.value = false
      }

    }
  })
}
</script>

<style scoped lang="less">
.auth-container {
  min-height: 100vh;
  display: flex;
}

/* 左侧图片展示区 */
.left-section {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('@/assets/image/login/login.jfif');
    background-size: cover;
    background-position: center;
    opacity: 0.15;
  }
}

.brand-content {
  position: relative;
  z-index: 1;
  color: white;
  max-width: 500px;
}

.brand-title {
  font-size: 48px;
  font-weight: 700;
  margin: 0 0 16px 0;
  line-height: 1.2;
}

.brand-subtitle {
  font-size: 20px;
  margin: 0 0 48px 0;
  opacity: 0.9;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 18px;
}

/* 右侧表单区 */
.right-section {
  flex: 0 0 500px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  box-shadow: -2px 0 20px rgba(0, 0, 0, 0.05);
}

.form-container {
  width: 100%;
  max-width: 400px;
}

.site-name {
  font-size: 42px;
  font-weight: 800;
  margin: 0 0 40px 0;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: 2px;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from {
  opacity: 0;
  transform: translateX(20px);
}

.fade-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

.form-header {
  margin-bottom: 32px;
  text-align: center;

  h2 {
    font-size: 28px;
    color: #1a1a1a;
    margin: 0 0 8px 0;
    font-weight: 700;
  }

  p {
    color: #666;
    margin: 0;
    font-size: 15px;
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.submit-btn {
  width: 100%;
  margin-top: 8px;
}

.form-footer {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e0e0e0;
  color: #666;
  font-size: 14px;

  span {
    margin-right: 8px;
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .left-section {
    padding: 40px;
  }

  .brand-title {
    font-size: 36px;
  }

  .brand-subtitle {
    font-size: 18px;
  }

  .right-section {
    flex: 0 0 450px;
  }
}

@media (max-width: 768px) {
  .auth-container {
    flex-direction: column;
  }

  .left-section {
    flex: 0 0 auto;
    min-height: 280px;
    padding: 40px 20px;
  }

  .brand-title {
    font-size: 32px;
  }

  .brand-subtitle {
    font-size: 16px;
    margin-bottom: 32px;
  }

  .feature-list {
    gap: 16px;
  }

  .feature-item {
    font-size: 16px;
  }

  .right-section {
    flex: 1;
    padding: 40px 20px;
  }

  .site-name {
    font-size: 36px;
    margin-bottom: 32px;
  }

  .form-header h2 {
    font-size: 24px;
  }
}
</style>
